using System;
using System.Globalization;
using System.Reflection;
using System.Web.UI;
using Sedna.Core.Security;
using log4net;
using Spring.Objects.Factory;

namespace Sedna.Core.Controller.Configurations
{
	/// <summary>
	/// Summary description for NumberStringDataParser.
	/// </summary>
	public class NumberStringDataParser: BaseDataTranslator, IInitializingObject
	{

		private ILog log=LogManager.GetLogger(typeof(NumberStringDataParser));

        private MethodInfo parseMethod;
	    
		protected IPrincipalWrapper principalWrapper;
		protected NumberStyles numberStyles=NumberStyles.Number; 
		protected Type numberType=typeof(Int32);
		protected object defaultValue;
	    

		public object DefaultValue
		{
			get { return defaultValue; }
			set { defaultValue = value; }
		}

		public IPrincipalWrapper PrincipalWrapper
		{
			get { return principalWrapper; }
			set { principalWrapper = value; }
		}

		public NumberStyles NumberStyles
		{
			get { return numberStyles; }
			set { numberStyles = value; }
		}

		public Type NumberType
		{
			get { return numberType; }
			set { numberType = value; }
		}


	    public void AfterPropertiesSet()
	    {
			if (numberType==null)
			{
				string errorMessage="NumberType is not specified.";
				log.Error(errorMessage);
				throw new ControllerConfigurationException(errorMessage);
			}	
	        
			parseMethod=numberType.GetMethod("Parse", BindingFlags.Static|BindingFlags.Public, null, new Type[]{typeof(string), typeof(NumberStyles), typeof(IFormatProvider)}, null);

			if (parseMethod==null)
			{
				string errorMessage="Parse() method not found. Probably, incorrect NumberType was specified. NumberType: "+numberType;
				log.Error(errorMessage);
				throw new ControllerConfigurationException(errorMessage);
			}
	        
	    }

	    protected override object GetDefaultValue(Control control, object value, Type targetType)
	    {
	        return defaultValue;
	    }

	    public override object UnsafeTranslate(Control control, object value, Type targetType)
	    {
			string parseString=value as string;
			if (parseString==null||parseString.Trim().Equals(String.Empty))
			{
				return defaultValue;
			}

//			try
//			{
				return parseMethod.Invoke(null, new object[]{parseString, numberStyles, principalWrapper.Culture});				
//			}
//			catch 
//			{
//				if (log.IsDebugEnabled)
//				{
//					log.Debug("Parsing exception was thrown. Returning unparsed  value: "+value);
//				}
//				return value;
//			}
		}



	}
}
